/**
 * Created by Administrator on 2016/7/1.
 */
import React from 'react';
import { bindActionCreators } from 'redux';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { NavBar, Carousel, Drawer } from 'antd-mobile';
import {
  getHomeList,
  getThemes,
  getTheme,
  getHomeNewsMore
} from '../actions/home';
import { HomeList } from '../components/HomeList';
import { Sidebar } from '../components/Sidebar';
import { agentImageURL, formatWeekDate } from '../utils';
import ReactList from 'react-list';

import '../assets/less/home.less';

const mapStateToProps = state => ({
  home: state.home
});

const mapDispatchTpProps = dispatch =>
  bindActionCreators(
    {
      getHomeList,
      getThemes,
      getTheme,
      getHomeNewsMore
    },
    dispatch
  );

/**
 * connect中间件
 * connect一定要写在需要传递参数的组件头部，因为这是语法规则，只对当前关联的组件生效，和java的原理是一致的
 * state用法：state => state（传递全部state）
 * dispatch用法：（单个action）bindActionCreators(navActions, dispatch)，（多个action）bindActionCreators({...action1, ...action2}, dispatch)
 */
class HomeContainer extends React.Component {
  constructor(props) {
    super(props);
    //构造函数用法
    //常用来绑定自定义函数，切记不要在这里或者组件的任何位置setState，state全部在reducer初始化，相信对开发的后期很有帮助
    //例子：this.myfunction = this.myfunction.bind(this)
    // this.handleClick = this.handleClick.bind(this)
    this.state = {
      isLoading: false,
      open: false,
      storiesList: [],
      myScroll: ''
    };
    this.onOpenChange = this.onOpenChange.bind(this);
    this.handleScroll = this.handleScroll.bind(this);
    this.renderItem = this.renderItem.bind(this);
  }

  onOpenChange = () => {
    this.setState({ open: !this.state.open });
  };

  async componentDidMount() {
    const { top_stories, stories } = this.props.home.homeList;
    if (stories || !stories.length || !top_stories || !top_stories.length) {
      await this.props.getHomeList();
    }
    await this.props.getThemes();

    this.handleScroll();
  }

  handleScroll = async () => {
    console.log(1111);
    await this.props.getHomeNewsMore(this.props.home.homeDate);
    // if (this.props.home.homeDate !== this.props.homeMoreNews.stories[this.props.homeMoreNews.stories.length - 1].date) {
    let data = [...this.state.storiesList, { ...this.props.home.homeMoreNews }];
    this.setState({
      storiesList: data
    });
  };

  renderItem = (index, key) => {
    console.log(222);
    // if (this.props.home.homeDate) {
    // this.handleScroll()
    if (this.state.storiesList[index]) this.handleScroll();
    return (
      <div key={key}>
        <div className="list-wrap">
          <div className="list-date">
            {this.state.storiesList.length ? (
              this.state.storiesList[index].date
            ) : null}
          </div>
        </div>
        {this.state.storiesList.length ? (
          this.state.storiesList[index].stories.map(story => {
            return (
              <HomeList
                key={story.id}
                id={story.id}
                imgUrl={
                  story.images && story.images[0] ? (
                    agentImageURL(story.images[0])
                  ) : (
                    ''
                  )
                }
                title={story.title}
              />
            );
          })
        ) : null}
      </div>
    );
    // }
  };

  render() {
    const { themes, homeList, editors } = this.props.home;
    // const {storiesList} = this.state
    const { top_stories, stories } = homeList;
    return (
      <div className="home-wrapper">
        <NavBar iconName="ellipsis" mode="dark" onLeftClick={this.onOpenChange}>
          首页
        </NavBar>
        <Drawer
          className="my-drawer"
          style={{ minHeight: document.documentElement.clientHeight - 45 }}
          contentStyle={{ color: '#A6A6A6', textAlign: 'center' }}
          sidebar={
            <Sidebar
              themes={themes}
              history={this.props.history}
              getTheme={() => this.props.getTheme()}
              onOpenChange={() => this.onOpenChange()}
            />
          }
          open={this.state.open}
          onOpenChange={this.onOpenChange}
        >
          <div id="scroll-container" ref="scrollContainer">
            {/*{JSON.stringify(top_stories)}*/}
            {// 轮播
            top_stories && top_stories.length > 1 ? (
              <Carousel
                autoplay={true}
                infinite
                selectedIndex={1}
                swipeSpeed={35}
              >
                {top_stories && top_stories.length > 1 ? (
                  top_stories.map((elem, index) => {
                    return elem.id ? (
                      <Link key={index} to={`/newsDetail/${elem.id}`}>
                        <div
                          className="carousel-item-wrap"
                          style={{
                            backgroundImage:
                              'url(' + agentImageURL(elem.image) + ')'
                          }}
                          key={index}
                        >
                          <p className="carousel-title">{elem.title}</p>
                        </div>
                      </Link>
                    ) : (
                      <div
                        className="carousel-item-wrap"
                        style={{
                          backgroundImage:
                            'url(' + agentImageURL(elem.image) + ')'
                        }}
                        key={index}
                      >
                        <p className="carousel-title">{elem.title}</p>
                      </div>
                    );
                  })
                ) : (
                  '没有数据'
                )}
              </Carousel>
            ) : top_stories && top_stories.length === 1 ? (
              <div>
                {top_stories && top_stories.length === 1 ? (
                  top_stories.map((elem, index) => {
                    return elem.id ? (
                      <Link key={index} to={`/newsDetail/${elem.id}`}>
                        <div
                          className="carousel-item-wrap"
                          style={{
                            backgroundImage:
                              'url(' + agentImageURL(elem.image) + ')'
                          }}
                          key={index}
                        >
                          <p className="carousel-title">{elem.title}</p>
                        </div>
                      </Link>
                    ) : (
                      <div
                        className="carousel-item-wrap"
                        style={{
                          backgroundImage:
                            'url(' + agentImageURL(elem.image) + ')'
                        }}
                        key={index}
                      >
                        <p className="carousel-title">{elem.title}</p>
                      </div>
                    );
                  })
                ) : (
                  '没有数据'
                )}
              </div>
            ) : (
              ''
            )}
            <div className="list-wrap">
              <div className="avatar-wrap">
                {editors ? <span>主编</span> : ''}
                {editors ? (
                  editors.map((item, index) => {
                    return (
                      <i
                        key={index}
                        style={{
                          backgroundImage:
                            'url(' + agentImageURL(item.avatar) + ')'
                        }}
                      />
                    );
                  })
                ) : (
                  ''
                )}
              </div>
              <div className="list-date">今日新闻</div>
              {stories ? (
                stories.map(item => {
                  return (
                    <HomeList
                      key={item.id}
                      id={item.id}
                      imgUrl={
                        item.images && item.images[0] ? (
                          agentImageURL(item.images[0])
                        ) : (
                          ''
                        )
                      }
                      title={item.title}
                    />
                  );
                })
              ) : (
                ''
              )}
            </div>
            <ReactList
              {...this.props}
              type="variable"
              itemRenderer={this.renderItem}
              items={this.state.storiesList}
              length={this.state.storiesList.length + 1}
            />
          </div>
        </Drawer>
      </div>
    );
  }
}

export default connect(mapStateToProps, mapDispatchTpProps)(HomeContainer);

HomeContainer.propTypes = {
  home: PropTypes.object,
  match: PropTypes.object.isRequired,
  location: PropTypes.object.isRequired
};
